package MianCalPak;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Blob;
import java.sql.ResultSet;
import java.util.Properties;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import DB.DBProvider;

/**
 * Servlet implementation class GetDesign
 */
public class GetDesign extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public GetDesign() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response); 
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String user = (String)request.getSession().getAttribute("username");
		String design = request.getParameter("designNumber");
		
		if ((user == null) || (design ==null)){
			response.sendError(HttpServletResponse.SC_BAD_REQUEST);
			return;
		}
		
		int designNumber = Integer.parseInt(design);
		
		if (designNumber == 1){
			response.sendRedirect("Calendar.xsl");
			return;
		}
		
		if (designNumber == 2){
			response.sendRedirect("Calendar2.xsl");
			return;
		}
		try{
			Properties p = new Properties();
	        p.load(getServletContext().getResourceAsStream("/WEB-INF/config"));
	        ResultSet res = (new DBProvider(p)).getXSlTFile(user,designNumber-2);
			
	        if (!res.next()){
	        	response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
	        	return;
	        }
	        
	        ServletOutputStream out = response.getOutputStream();
	        response.setContentType("text/xml");
	        Blob file = res.getBlob("xslt_file");
	        InputStream in = file.getBinaryStream();
			int length = (int) file.length();
	        int bufferSize = 1024;
	        byte[] buffer = new byte[bufferSize];
	        while ((length = in.read(buffer)) != -1) {
	        out.write(buffer, 0, length);
	        }
		}

			catch (Exception e) {
				response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
				e.printStackTrace();} 
	}

}
